import { forwardRef, useImperativeHandle, useState } from 'react';

import { useAntdTable } from 'ahooks';
import { Button, Drawer, Form, Input, Select, Space, Table } from 'antd';

import Filter from '@/components/filter';

import { store } from '@/store';

import { TimeSort } from '@/enum';
import { equInfoPage } from '@/services/bizApi/shebaoxinxijiekou';

import { BizObject } from './';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: (arr: any[]) => void;
};

export type DeviceRef = {
  open: (arg: EditOpenBaseArgs & { manageDeptId?: string }) => void;
};

export type EditProps = {};

const Device: React.ForwardRefRenderFunction<DeviceRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<DeviceRef['open']>[0]>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRows, setSelectedRows] = useState<BIZAPI.EquInfoEntity[]>([]);
  const [filter] = Filter.useForm();
  const table = useAntdTable(
    async ({ current, pageSize }, { id, ...formData }) => {
      const res = await equInfoPage({
        ...formData,
        ...id,
        manageDeptId: args?.manageDeptId,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序
      });

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);
        form.resetFields();
        table.search.submit();
      }
    };
  });

  const onCancel = () => {
    setOpen(false);
    setSelectedRowKeys([]);
    setSelectedRows([]);
  };

  // 仅保存
  const onSave = () => {
    args?.onSuccess?.(selectedRows || []);
    setOpen(false);
    setSelectedRowKeys([]);
    setSelectedRows([]);
  };

  return (
    <Drawer
      title="设备"
      extra={
        <Space>
          <Button type="primary" onClick={onSave}>
            保存
          </Button>
          <Button onClick={onCancel}>取消</Button>
        </Space>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      {/* 筛选 */}
      <Filter onFinish={onSearch} form={filter}>
        <Filter.Item name="manageDeptId" hidden>
          <Input
            style={{
              width: 160
            }}
            placeholder="请输入使用部门id"
          />
        </Filter.Item>
        <Filter.Item name="equipmentName">
          <Input
            style={{
              width: 160
            }}
            placeholder="请输入设备名称"
          />
        </Filter.Item>
        <Filter.Item name="equipmentCode">
          <Input
            style={{
              width: 160
            }}
            placeholder="请输入设备编号"
          />
        </Filter.Item>
        <Filter.Item name="specification">
          <Input
            style={{
              width: 160
            }}
            placeholder="请输入规格型号"
          />
        </Filter.Item>
        <Filter.Item name="productionSite">
          <Select
            style={{
              width: 160
            }}
            allowClear
            placeholder="请选择生产站点"
            options={(store.dict['productionSite'] || []).map((item) => ({
              value: item.dicValue,
              label: item.dicName
            }))}
          />
        </Filter.Item>
        <Filter.Item name="processSection">
          <Select
            style={{
              width: 160
            }}
            allowClear
            placeholder="请选择工艺段"
            options={(store.dict['processSection'] || []).map((item) => ({
              value: item.dicValue,
              label: item.dicName
            }))}
          />
        </Filter.Item>
        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={[
          {
            title: '设备名称',
            dataIndex: 'equipmentName'
          },
          {
            title: '设备编号',
            dataIndex: 'equipmentCode'
          },
          {
            title: '规格型号',
            dataIndex: 'specification',
            width: 300
          },
          {
            title: '生产站点',
            dataIndex: 'productionSite'
          },
          {
            title: '工艺段',
            dataIndex: 'processSection'
          },
          {
            title: '使用状态',
            dataIndex: 'useStatus'
          },
          {
            title: '使用人员',
            dataIndex: 'useUserName'
          },
          {
            title: '设备等级',
            dataIndex: 'equipmentLevel'
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        rowSelection={{
          selectedRowKeys,
          onChange: (keys: React.Key[], rows) => {
            setSelectedRowKeys(keys);
            setSelectedRows(rows);
          }
        }}
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* end表格 */}
    </Drawer>
  );
};

export default forwardRef(Device);
